<template>
  <div class="content-container">
    <ButtonGroup v-if="showBtn" class="top" :options="topButtons" @click="handleButtonClick" />
    <p-table
      :custom-header-row="customHeaderRowMinxin"
      row-key="id"
      :columns="columns"
      bordered
      :loading="loading"
      :scroll="getScroll"
      :data-source="dataSource"
      :pagination="false"
      :row-selection="getRowSelection"
      @change="handleTableChange"
    >
      <template slot="professionName" slot-scope="text, record, index">
        <InputDefault
          :value="text"
          :is-edit="record.isEdit"
          @change="
            handleInputChange($event, text, record, index, 'professionName')
          "
        />
      </template>
      <template slot="state" slot-scope="text, record, index">
        <SelectCustomer
          :value="text"
          :has-all="false"
          :is-edit="showBtn"
          :options="stateOptions"
          :select-type="selectType"
          :allow-clear="false"
          @input="handleInputChange($event, text, record, index, 'state')"
        />
      </template>
    </p-table>
    <!-- <ButtonGroup
      class="footer"
      :options="footerButtons"
      @click="handleButtonClick"
    /> -->
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import {
  postProfessionInsert,
  postProfessionListByPage,
  postProfessionDelete,
} from '@/api/customerApi.js';

import { deepClonel } from '@/utils/index';

// let index = 0;
const createDefaultItem = () => ({
  // id: index++,
  // customerCode: '',
  professionName: '',
  state: '',
});

export default {
  components: {},
  mixins: [mixinTable],
  props: {
    value: {
      type: String,
      default: '',
    },
    code: {
      type: String,
      default: '',
    },
    // isEdit: {
    //   type: Boolean,
    //   default: true,
    // },
    // dataSource: {
    //   type: Array,
    //   default: () => [],
    // },
    rowSelection: {
      type: Object,
      default: () => {},
    },
    showBtn: {
      type: Boolean,
      default: false
    },
    isNewPrice: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    keyTabs: {
      type: String,
      default: '2',
    },
  },
  data() {
    return {
      stateOptions: [
        {
          label: '有效',
          value: true,
        },
        {
          label: '失效',
          value: false,
        },
      ],
      selectType: {
        true: '有效',
        false: '失效',
      },
      columnKey: '',
      asc: true,
      dataSource: [],
      listSoure: [],
      // newDataList: []
    };
  },
  computed: {
    getScroll() {
      return this.showBtn ? { x: '100%', y: '53vh' } : { x: '100%', y: 300 }
    },
    getRowSelection() {
      return this.showBtn ? this.rowSelectionMixin : this.rowSelection
    },
    topButtons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          label: '新增业务线',
          type: 'primary',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          type: '',
          icon: 'delete',
          disabled,
        },
      ];
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 30,
          customRender: (t, r, index) => {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '业务线',
          dataIndex: 'professionName',
          key: 'professionName',
          width: 100,
          required: true,
          sorter: true,
          ellipsis: true,
          scopedSlots: { customRender: 'professionName' },
        },
        {
          align: 'center',
          title: '状态',
          dataIndex: 'state',
          key: 'state',
          width: 60,
          required: true,
          sorter: true,
          ellipsis: true,
          scopedSlots: { customRender: 'state' },
        },
        {
          align: 'center',
          title: '创建人',
          dataIndex: 'createUserName',
          key: 'createUserName',
          width: 80,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 100,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改人',
          dataIndex: 'updateUserName',
          key: 'updateUserName',
          width: 80,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          width: 100,
          sorter: true,
          ellipsis: true,
        },
      ];
      return columns;
    },
  },
  watch: {
    keyTabs: {
      handler(newVal) {
        newVal === '2' && this.init();
      },
      immediate: true,
    },
  },
  created() {
    // this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.getProfessionListByPage({
        customerCode: this.code,
      });
    },
    async getProfessionListByPage({ customerCode }) {
      // const page = this.getParams();
      this.loading = true;
      const res = await postProfessionListByPage({
        customerCode,
      }).finally(() => (this.loading = false));
      let dataSource = res?.data?.data || [];
      dataSource.length && dataSource?.forEach((item) => {
        item['isEdit'] = false
      })
      this.listSoure = deepClonel(res?.data?.data) || [];
      this.dataSource = dataSource || [];
      // console.log(this.dataSource,'123')
      // this.paginationMixin.total = res?.data?.data?.total;
    },
    getParams() {
      const page = {
        // current: this.paginationMixin.current,
        // pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return page;
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      // console.log(page,sorter);
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      // this.paginationMixin = page;
      this.getProfessionListByPage({customerCode: this.code});
    },
    // onClose() {
    //   this.$emit('change', false);
    //   // this.$emit('fresh');
    // },
    // // 返回
    // closeCallback() {
    //   this.onClose();
    // },
    handleInputChange(e, text, record, index, key) {
      this.dataSource[index][key] = e;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      // console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    async deleteCallback() {
      let allId = this.listSoure.length && this.listSoure?.map(item => item.id) || [];
      // console.log(allId, 'id1qwe');
      let deleteList = this.rowSelectionMixin.selectedRowKeys || [];
      let a = new Set(allId);
      let b = new Set(deleteList);
      let vals = [...new Set([...a])];
      let oldList = vals.filter(x => b.has(x));

      // let oldList = deleteList?.filter(item => {
      //   return allId.includes(item);
      // });
    
      let newList = deleteList?.filter(item => {
        return !allId.includes(item);
      });
      if (!deleteList.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      if (oldList.length && newList.length) {
        this.$message.error('请先保存新增的数据,再进行数据删除！');
        return;
      }
      if (newList.length) {
        // console.log(this.dataSource, this.dataSource.length, '1');
        newList.forEach(id => {
          const index = this.dataSource.findIndex(item => item.id === id);
          this.dataSource.splice(index, 1);
        });
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        return;
      }

      this.$confirm(`该操作将删除 ${deleteList.length} 条数据，是否确认？`)
        .then(async () => {
          if (oldList.length) {
            const res = await postProfessionDelete(oldList);
            if (res?.data?.data) {
              this.$message.success('删除成功');
              // this.paginationMixin.current = 1
              this.getProfessionListByPage({ customerCode: this.code });
            } else {
              this.$message.error('删除失败');
            }
            // console.log(oldList)
          }
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch((err) => {
          console.log(err);
        });
        // console.log(this.rowSelectionMixin.selectedRowKeys, 'lop');
      // console.log(this.dataSource, '2');
    },
    addCallback() {
      this.dataSource.push({ ...createDefaultItem(), customerCode: this.code });
      // console.log(this.dataSource, 'this.dataSource.');
      // console.log(this.listSoure, 'this.listSoure.');
    },
    getSourceData() {
      let dataList = this.dataSource || [];
      let data = dataList?.filter(item => {
        return !item.id;
      });
      return data;
    },
    getIsValid() {
      this.rowSelectionMixin.selectedRowKeys = [];
      let data = this.getSourceData();
      const isValid = data?.every(
        item => item.professionName && String(item.state)
      );
      if (!isValid) {
        this.$message.error('请将新增数据填写完整！');
        return false;
      }
      return true;
    },
    async submitCallback() {
      // let info = this.getSourceData() || [];
      // let data = [...this.listSoure, ...info] || []
      if (!this.getIsValid()) {
        return;
      }
      // console.log(this.dataSource);
      const res = await postProfessionInsert(this.dataSource);
      if (res?.data?.data) {
        this.$message.success('提交成功！');
        this.getProfessionListByPage({ customerCode: this.code });
      }
    },
    async saveCallback() {
      // let info = this.getSourceData() || [];
      // let data = [...this.listSoure, ...info] || []
      console.log(this.dataSource, '123data');
      if (!this.getIsValid()) {
        return;
      }
      // console.log(dataList);
      const res = await postProfessionInsert(this.dataSource);
      if (res?.data?.data) {
        this.$message.success('保存成功！');
        this.getProfessionListByPage({ customerCode: this.code });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content-container {
  width: 100%;
  .top {
    margin-bottom: 15px;
  }
  .footer {
    width: 100%;
    position: absolute;
    z-index: 100;
    background: #fff;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #e5e6e9;
  }
}
</style>
